import formmatDate from '.././DdFormmatDate/index.ts';
function exportCsv(
  headerLabel: any = [],
  headerProp: any = [],
  data: any = [],
  fileName: string = 'ddElement',
  isTime: boolean = true
) {
  if (!data || data.length <= 0) {
    console.error('data is not undefined');
    return;
  }
  if (!headerLabel || headerLabel.length <= 0) {
    console.error('headerLabel is not undefined');
    return;
  }
  if (!headerProp || headerProp.length <= 0) {
    console.error('headerProp is not undefined');
    return;
  }
  let csvContent = 'data:text/csv;charset=utf-8,\ufeff';
  csvContent += headerLabel + '\n';
  data.forEach((item, index) => {
    let dataString = '';
    for (const prop of headerProp) {
      dataString += item[prop] + ',';
    }
    csvContent +=
      index < data.length
        ? dataString.replace(/,$/, '\n')
        : dataString.replace(/,$/, '');
  });

  const link = document.createElement('a'); // 创建a标签
  link.download = isTime
    ? fileName + ' ' + formmatDate(new Date(), 'yyyy-MM-dd hh:mm:ss') + '.csv'
    : fileName + '.csv';
  link.style.display = 'none';
  link.setAttribute('href', encodeURI(csvContent));
  document.body.appendChild(link);
  link.click(); // 执行下载
  URL.revokeObjectURL(link.href); // 释放url
  document.body.removeChild(link); // 释放标签
}

export default exportCsv;
